﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.IO;
using System.Net;

using XMK.Tadong.Model;
using XMK.Tadong.Biz;
using XMK.Utils;
using XMK.Framework.Model;
using XMK.Tadong.Model.Cond;
using XMK.Tadong.Web.Language;
using System.Configuration; 
using System.Data;
using HU8.Helpers.Files;
using HU8.Helpers.Base;
namespace XMK.Tadong.Web.Views.DataSearch
{
    public partial class WatchFileView : FileExplorerPage
    {
        public string PageNum;
        public string swfpath;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string spaceType = Request.Params.Get("space_type");
                if (string.IsNullOrWhiteSpace(spaceType)) h_spaceType.Value = "30";
                else
                    h_spaceType.Value = spaceType;
                

                if (XMKFileExtInfoModel == null
                || string.IsNullOrWhiteSpace(XMKFileExtInfoModel.FILE_NAME.Trim()))
                {
                    _xmkFileExtInfoModel = new XMKFileExtInfo
                    {
                        FILE_NAME = string.Empty,
                        SwfFilePath = string.Empty
                    };
                    ClientScript.RegisterStartupScript(this.GetType(),
                        "alertclose", "<script> alert(" + lang.Get("Time consuming") + "); window.close();</script>");
                }
                else
                {
                    WriteLog(LogOperateType.ScanFile, XMKFileExtInfoModel.FILE_NAME);
                }
            }



            string hiddenDownload = Request.QueryString["hiddenDownload"];
            if (!string.IsNullOrEmpty(hiddenDownload))
            {
                if (hiddenDownload == "single")
                {
                    btnDownloadSourceFile_Click(null, null);
                }
                else
                {
                    FileDownloadList(hiddenDownload);
                }
            }
            
        }

        private XMKFileExtInfo _xmkFileExtInfoModel;
        public XMKFileExtInfo XMKFileExtInfoModel
        {
            get
            {
                string DiskPath = ConfigurationManager.AppSettings["DiskPath"];
                if (_xmkFileExtInfoModel == null)
                {
                    _xmkFileExtInfoModel = new XMKFileExtInfo {
                        FILE_NAME = String.Empty,
                        SwfFilePath = string.Empty
                    };

                    string fileID = Request.QueryString["id"];
                    if (!string.IsNullOrWhiteSpace(fileID))
                    {
                        if (h_spaceType.Value.Equals("30"))
                        {
                            Tb_Xmk_FileBiz biz = new Tb_Xmk_FileBiz();
                            _xmkFileExtInfoModel = biz.GetXMKFileExtInfoByID(fileID);
                            swfpath = DiskPath + _xmkFileExtInfoModel.SwfFilePath;
                            try
                            {
                                string[] list = Directory.GetFiles(swfpath);
                                PageNum = list.Length.ToString();
                            }
                            catch(Exception e)
                            {
                                ClientScript.RegisterStartupScript(this.GetType(),
                               "alertclose", "<script> alert(" + lang.Get("File converting") + "); window.close();</script>");
                            }
                        }
                        else if (h_spaceType.Value.Equals("20"))
                        {
                            TB_TEAM_FILEBiz teamBiz = new TB_TEAM_FILEBiz();
                            _xmkFileExtInfoModel = teamBiz.GetModelByFileId(fileID);
                            swfpath = DiskPath + _xmkFileExtInfoModel.SwfFilePath;
                            try
                            {
                                string[] list = Directory.GetFiles(swfpath);
                                PageNum = list.Length.ToString();
                            }
                            catch (Exception e)
                            {
                                ClientScript.RegisterStartupScript(this.GetType(),
                               "alertclose", "<script> alert(" + lang.Get("File converting") + "); window.close();</script>");
                            }
                        }
                        else 
                        {
                            TB_PERSON_FILEBiz perBiz = new TB_PERSON_FILEBiz();
                            _xmkFileExtInfoModel = perBiz.GetModelByFileId(fileID);
                            swfpath = DiskPath + _xmkFileExtInfoModel.SwfFilePath;
                            try
                            {
                                string[] list = Directory.GetFiles(swfpath);
                                PageNum = list.Length.ToString();
                            }
                            catch(Exception e)
                            {
                                ClientScript.RegisterStartupScript(this.GetType(),
                               "alertclose", "<script> alert(" + lang.Get("File converting") + "); window.close();</script>");
                            }
                        }
                        if (_xmkFileExtInfoModel != null)
                        {
                            if (!string.IsNullOrWhiteSpace(_xmkFileExtInfoModel.SwfFilePath))
                            {
                                string fileServerSite = ConfigurationManager.AppSettings["fileServerSite"];
                                swfpath = fileServerSite + _xmkFileExtInfoModel.SwfFilePath;
                                
                                _xmkFileExtInfoModel.SwfFilePath = Path.Combine(Config.FileServerSite, _xmkFileExtInfoModel.SwfFilePath).Replace("\\", "/");
                            }
                            if (!string.IsNullOrWhiteSpace(_xmkFileExtInfoModel.PDFFilePath))
                            {
                                _xmkFileExtInfoModel.PDFFilePath = Path.Combine(Config.DiskFilePath, _xmkFileExtInfoModel.PDFFilePath).Replace("\\", "/");
                            }
                            if (!string.IsNullOrWhiteSpace(_xmkFileExtInfoModel.SAVE_PATH))
                            {
                                _xmkFileExtInfoModel.SAVE_PATH = Path.Combine(Config.DiskFilePath, _xmkFileExtInfoModel.SAVE_PATH).Replace("\\", "/");
                            }
                            string fileExt = Path.GetExtension(_xmkFileExtInfoModel.SAVE_PATH);
                           
                            EXTBiz biz = new EXTBiz();
                            ExtTypeinfo extcode = biz.getExtCodeByExtent(fileExt.Replace(".", ""));
                            if (extcode != null)
                            {
                                ImgFileIcon.Src = string.Format("../../WebFileExplorer/images/ico/exttype/" + extcode.PIC_NAME, extcode.EXT_CODE);
                            }
                            else
                            {
                                ImgFileIcon.Src = string.Format("../../WebFileExplorer/images/ico/exttype/130901108129_2486.png", "unkown");
                            }
                        }
                    }
                }
                return _xmkFileExtInfoModel;
            }
        }


        protected bool CheckUserAuthority(int rightLevel)
        {
            
            Base_FileRoleOper fileRoleOper = new Base_FileRoleOper();
            if (h_spaceType.Value.ToString() == "30")
            {
                if (rightLevel == 2)
                {//下载pdf
                    fileRoleOper.FileId = Request.QueryString["id"];//"4209";
                    fileRoleOper.SpaceType = "30";
                    fileRoleOper.OpreType = "20";
                }
                else if (rightLevel == 3)
                { //下载源文件
                    fileRoleOper.FileId = Request.QueryString["id"];//"4209";
                    fileRoleOper.SpaceType = "30";
                    fileRoleOper.OpreType = "30";
                }
            }
            else if (h_spaceType.Value.ToString() == "20")
            {
                if (rightLevel == 2)
                {//下载pdf
                    fileRoleOper.FileId = Request.QueryString["id"];//"4209";
                    fileRoleOper.SpaceType = "20";
                    fileRoleOper.OpreType = "20";
                }
                else if (rightLevel == 3)
                { //下载源文件
                    fileRoleOper.FileId = Request.QueryString["id"];//"4209";
                    fileRoleOper.SpaceType = "20";
                    fileRoleOper.OpreType = "30";
                }
            }
            else if (h_spaceType.Value.ToString() == "10")
            {
                return true;
            }
            Base_DictBiz dictBiz = new Base_DictBiz();
            ResponseInfo resp = dictBiz.GetUserFileRoleRight(fileRoleOper);
            if ((bool)resp.Data == true)
                return true;
            return false;
        }

        protected void btnDownloadSourceFile_Click(object sender, EventArgs e)
        {
            if (CheckUserAuthority(3))
            {
                FileDownload(XMKFileExtInfoModel.SAVE_PATH, XMKFileExtInfoModel.FILE_NAME);
                WriteLog(LogOperateType.DownFile, XMKFileExtInfoModel.FILE_NAME);
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(),
                    "alertclose", "<script> alert(" + lang.Get("Insufficient_permissions_contact_your_administrator") + "); </script>");
            }
        }

        private void FileDownload(string filePath,string File_Name)
        {
            byte[] bytes;
            //以字符流的形式下载文件
            string fileName = Path.GetFileName(filePath);
            using (FileStream fs = new FileStream(filePath, FileMode.Open))
            {
                
                bytes = new byte[(int)fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();
            }

            Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(File_Name, System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }
        private void FileDownloadList(string paths)
        {
           
            JsonResponse downloadRes = new JsonResponse();
            JsonResponse response;
            string sourcepath = ConfigurationManager.AppSettings["DiskPath"];
            string strTmpDir = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "Temp\\";
            string strTmpDir1=strTmpDir.Replace("\\","/");
            string strTmpDirZip = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "TempZip\\";
            string[] pathss = paths.Split(',');
            Directory.CreateDirectory(strTmpDir);
            Directory.Delete(strTmpDir, true);
            Directory.CreateDirectory(strTmpDir);
            Tb_Xmk_FileBiz bll = new Tb_Xmk_FileBiz();
            DataTable dt = bll.GetModelList(paths);
            string sourcdownepath = "";
            string nowfilepath = "";
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    sourcdownepath += sourcepath + dt.Rows[i]["file_name"].ToString() + ","; //sourcepath + dt.Rows[i]["save_path"].ToString() + ",";
                    File.Copy(sourcepath + dt.Rows[i]["save_path"].ToString(), strTmpDir + dt.Rows[i]["file_name"].ToString());
                    nowfilepath += strTmpDir + dt.Rows[i]["file_name"].ToString() + ",";
                }
            }
            string relativePath = Path.Combine(GetTempPath(), string.Format("Download_{0}.zip", DateTime.Now.ToString("yyyyMMdd_hhmmss")));
            string absolutePath = VirtualPathUtility.ToAbsolute(relativePath);
            string dest = Server.MapPath(relativePath);
            response = ZipHelper.GenerateZipFile(nowfilepath, dest, "", true);

            byte[] bytes;
            //以字符流的形式下载文件
            string fileName = dest.Substring(dest.LastIndexOf("\\"));
            using (FileStream fs = new FileStream(dest, FileMode.Open))
            {

                bytes = new byte[(int)fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();
            }

            Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
            
        }
        public string GetTempPath()
        {
            string p = "~/Temp";
            string serverPath = Server.MapPath(p);
            if (!Directory.Exists(serverPath))
            {
                Directory.CreateDirectory(serverPath);
            }
            return p;
        }
        protected void btnDownloadPDF_Click(object sender, EventArgs e)
        {
            if (CheckUserAuthority(2))
            {
                FileDownload(XMKFileExtInfoModel.PDFFilePath, XMKFileExtInfoModel.FILE_NAME.Substring(0,XMKFileExtInfoModel.FILE_NAME.LastIndexOf('.')) + ".pdf");
                WriteLog(LogOperateType.DownFile, XMKFileExtInfoModel.FILE_NAME);
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(),
                    "alertclose", "<script> alert(" + lang.Get("Insufficient_permissions_contact_your_administrator") + "); </script>");
            }
        }

        private void WriteLog(LogOperateType operateType, string fileName)
        {
            //string operateDesc = operateType == LogOperateType.ScanFile ? "浏览" : "下载";
            //string spaceName = h_spaceType.Value.Equals("20") ? "课题组" : "项目库";
            //XMKLogInfo logModel = new XMKLogInfo();
            //logModel.DataId = XMKFileExtInfoModel.FILE_ID;
            //logModel.Keyword = fileName;
            //logModel.LogDesc = string.Format("【{0}】【{1}】{3}了{4}文件,{2}",
            //    LoginUserBiz.LoginUserName(), LoginUserBiz.LoginUserAccount(), fileName, operateDesc, spaceName);
            //logModel.OperateTime = DateTime.Now;
            //logModel.OperateType = operateType;
            //logModel.UserId = LoginUserBiz.LoginUserID();
            //logModel.IP = Request.ServerVariables["REMOTE_ADDR"].Equals("::1") ? "127.0.0.1" : Request.ServerVariables["REMOTE_ADDR"];
            long fileid = XMKFileExtInfoModel.FILE_ID;
            string ip = Request.ServerVariables["REMOTE_ADDR"].Equals("::1") ? "127.0.0.1" : Request.ServerVariables["REMOTE_ADDR"];
            XMKLogBiz.WriteLogFile(operateType, fileName, fileid, h_spaceType.Value,ip);
        }
    }
}